import axios from 'axios'
import store from '@/store'
import storage from 'store'
import notification from 'ant-design-vue/es/notification'
import message from 'ant-design-vue/es/message'
import {VueAxios} from './axios'
import {ACCESS_TOKEN} from '@/store/mutation-types'
import qs from "qs";

// 站点配置文件
// window.publicConfig => public/config.js
const publicConfig = store.getters.publicConfig

// 创建 axios 实例
const service = axios.create({
    // 服务端api地址
    // baseURL: process.env.NODE_ENV === 'production' ? publicConfig.BASE_API : process.env.VUE_APP_API_BASE_URL,
    baseURL: publicConfig.BASE_API,
    timeout: 60 * 1000, // 请求超时时间，60秒, 如果上传大文件需要更长
    // 关键：全局自定义数组序列化方式
    paramsSerializer: params => qs.stringify(params, {indices: false})
})

// 接口请求拦截
service.interceptors.request.use(config => {
    // 设置每个请求的Content-Type
    // config.headers['Content-Type'] = 'application/json;charset=utf-8'

    // 让每个请求携带当前用户token
    const token = storage.get(ACCESS_TOKEN)
    if (token) {
        config.headers['Authorization'] = 'Bearer ' + token
    }
    return config
})

// 是否显示未登录提示
let notLoggedMessage = false

// 接口响应拦截
service.interceptors.response.use((response) => {
        // 判断是否为二进制下载
        const contentType = response.headers['content-type']
        if (
            response.config.responseType === 'blob' ||
            response.config.responseType === 'arraybuffer' ||
            (contentType && (contentType.includes('application/octet-stream') || contentType.includes('application/vnd')))
        ) {
            // 获取文件名
            let filename = 'download'
            const disposition = response.headers['content-disposition']
            if (disposition) {
                const match = disposition.match(/filename="?([^"]+)"?/)
                if (match) filename = decodeURIComponent(match[1])
            }
            // 创建Blob并下载
            const blob = new Blob([response.data])
            const link = document.createElement('a')
            link.href = window.URL.createObjectURL(blob)
            link.download = filename
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
            window.URL.revokeObjectURL(link.href)
            // 返回一个标记，防止后续处理
            return Promise.resolve({downloaded: true})
        }
        return response.data
    }, (error) => {
        const errorMsg = ((error.response || {}).data || {}).detail || error.message || '请求出现错误，请稍后再试'
        if (error.response) {
            const {response: {status, data}} = error
            if (status) {
                if (status === 500) {
                    message.error(errorMsg, 1.8)
                    return Promise.reject(data)
                }
                // 鉴权失败: 未登录
                if (status === 401) {
                    if (!notLoggedMessage) {
                        notLoggedMessage = true
                        store.dispatch('Logout').then(() => {
                            notification.error({
                                key: 'notLoggedMessage',
                                message: '错误',
                                description: errorMsg,
                                duration: 3
                            })
                            setTimeout(() => window.location.reload(), 1500)
                        })
                    }
                }
            }
        }
        // 网络请求出错
        notification.error({
            message: '网络请求出错',
            description: errorMsg,
            duration: 3
        })
        return Promise.reject(error)
    }
)

const installer = {
    vm: {},
    install(Vue) {
        Vue.use(VueAxios, service)
    }
}

export {
    installer as VueAxios,
    service as axios
}
